package com.example.clock.controller;

import com.example.clock.entity.AttendVo;
import com.example.clock.service.AttendService;
import com.example.clock.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Controller
@RequestMapping("/pc")
public class pcController {

    private static final Logger logger = LoggerFactory.getLogger(pcController.class);

    @Autowired
    private AttendService attendService;

    //上下班打卡
    @PostMapping("/clocktodo")
    public String clock(String userName, String clockTime, Model model) throws UnsupportedEncodingException {
        LocalDateTime date = LocalDateTime.now();
        if (clockTime != null && !clockTime.isEmpty()) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
            date = LocalDateTime.parse(clockTime, formatter);
        }
        if (userName == null || userName.isEmpty()) {
            userName = "username";
        }
        String msg = attendService.clock(userName, date);
        model.addAttribute("msg", msg);

        return "redirect:/pc/getClockList?&userName=" + userName;
    }

    @GetMapping("/getClockList")
    public String getClockList(String userName, Integer year, Integer month, Model model) throws ParseException {
        LocalDate sTime;
        LocalDate eTime;
        LocalDate localDate = LocalDate.now();

        if (year == null && month == null) {
            year = localDate.getYear();
            month = localDate.getMonthValue();
            sTime = localDate.withDayOfMonth(1);
            eTime = localDate.withDayOfMonth(LocalDate.now().lengthOfMonth());
        } else {
            //指定月份的
            sTime = localDate.withYear(year).withMonth(month).withDayOfMonth(1);
            eTime = localDate.withMonth(month).withDayOfMonth(LocalDate.now().withMonth(month).lengthOfMonth());
        }
        AttendVo data = attendService.getThisMonthClockList(userName, sTime, eTime);
        model.addAttribute("data", data);
        model.addAttribute("userName", userName);
        model.addAttribute("monthValue", month);
        model.addAttribute("yearValue", year);
        return "pcClock";
    }
}
